package com.example.cunion.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cunion.entity.Chat;
import com.example.cunion.entity.Chat;
import com.example.cunion.entity.User;
import com.example.cunion.exception.CunionException;
import com.example.cunion.mapper.ChatMapper;
import com.example.cunion.mapper.UserMapper;
import com.example.cunion.service.ChatService;
import com.example.cunion.util.HtmlUtil;
import com.example.cunion.util.MarkdownUtil;
import com.example.cunion.util.StringSnowflakeIdGenerator;
import com.example.cunion.webSocket.WebSocketServerEndpoint;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
* @author Aero
* @description 针对表【chat(ai聊天表)】的数据库操作Service实现
* @createDate 2023-10-15 15:04:04
*/
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat>
    implements ChatService{

    @Resource
    private ChatMapper chatMapper;

    @Resource
    private UserMapper userMapper;


    @Override
    public Integer sendInfo(HashMap<String, Object> map) {
        MarkdownUtil markdownUtil = new MarkdownUtil();
        String content = map.get("content").toString();
        String tempString = map.get("content").toString();
        StringSnowflakeIdGenerator stringSnowflakeIdGenerator = new StringSnowflakeIdGenerator(1, 1);
        String id = stringSnowflakeIdGenerator.nextId();
        map.put("id", id);
        if (!"88888888".equals(map.get("receiverId").toString())){
            String isImg = map.get("is_img").toString();
            if ("0".equals(isImg)){
                String toMarkdown = markdownUtil.convertToMarkdown(tempString);
                map.replace("content", toMarkdown);
            }
            map.put("isImg", Integer.parseInt(isImg));
            map.put("isAi", 0);
            Integer result = chatMapper.sendInfo(map);
            // 将HashMap转换为JSON字符串
            String jsonString = new JSONObject(map).toString();
            WebSocketServerEndpoint webSocketServerEndpoint = new WebSocketServerEndpoint();
            try {
                webSocketServerEndpoint.onMessage(jsonString, null);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (result != 1){
                throw new CunionException("消息发送失败！");
            }
            return result;
        }
        map.put("isAi", 1);
        map.replace("receiverId", "88888888");
        chatMapper.sendInfo(map);
        // 将HashMap转换为JSON字符串
        String jsonString = new JSONObject(map).toString();
        WebSocketServerEndpoint webSocketServerEndpoint = new WebSocketServerEndpoint();
        try {
            webSocketServerEndpoint.onMessage(jsonString, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
//        GptApiClient gptApiClient = new GptApiClient("sk-tO7p7Vct43etPveFloowyelaR3CPfvgZR69GpCzhTa7dqpW7");
//        String answerResult = gptApiClient.getChatGptResult(content);
//        JSONObject bean = JSONUtil.toBean(answerResult, JSONObject.class);
//        String choices = bean.get("choices").toString();
//        List<String> list = JSONUtil.toList(choices, String.class);
//        JSONObject jsonObject = JSONUtil.toBean(list.get(0), JSONObject.class);
//        String message = jsonObject.get("message").toString();
//        JSONObject object = JSONUtil.toBean(message, JSONObject.class);
//        System.out.println(object.get("content"));
//        String convertToMarkdown = markdownUtil.convertToMarkdown(object.get("content").toString());
//        String bootId = stringSnowflakeIdGenerator.nextId();
//        hashMap.put("id", bootId);
//        hashMap.put("senderId", "88888888");
//        hashMap.put("receiverId", map.get("senderId").toString());
//        hashMap.put("content", convertToMarkdown);
//        hashMap.put("isAi", 1);
        Integer result = chatMapper.sendInfo(hashMap);
        // 将HashMap转换为JSON字符串
        String string = new JSONObject(hashMap).toString();
        try {
            webSocketServerEndpoint.onMessage(string, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (result != 1){
            throw new CunionException("提问失败！");
        }
        return result;
    }


    @Override
    public List<HashMap> searchInfoHistory(HashMap map) {
        List<HashMap> list = chatMapper.searchInfoHistory(map);
        for (int i = list.size() - 1; i >= 0 ; i--) {
            if ("88888888".equals(list.get(i).get("sender_id").toString())){
                String content = list.get(i).get("content").toString();
                list.get(i).replace("content", "");
                list.get(i).put("botContent", content);
            }else {
                list.get(i).put("botContent", "");
            }
        }
        Collections.reverse(list);
        return list;
    }

    @Override
    public List<HashMap> searchMyMessage(String id, String senderId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("senderId", senderId);
        List<HashMap> list = chatMapper.searchMyMessage(hashMap);
        for (HashMap map : list){
            String isRead = map.get("is_read").toString();
            if (isRead.equals("0")){
                String string = map.get("id").toString();
                chatMapper.updateStatus(string);
            }
            if (map.get("sender_id").equals(id)){
                map.put("botContent", "");
            }else {
                map.put("botContent", map.get("content").toString());
                map.replace("content", "");
            }
        }
        Collections.reverse(list);
        return list;
    }

    @Override
    public List<User> searchPrivateChatObject(String id) {
        List<HashMap> list = chatMapper.searchPrivateChatObject(id);
        Set<User> userSet = new HashSet<>();
        for (HashMap map : list){
            String receiverId = map.get("receiverId").toString();
            String senderId = map.get("senderId").toString();
            if (receiverId.equals(id)){
                User user = userMapper.getLoginUser(senderId);
                userSet.add(user);
            }else {
                User user = userMapper.getLoginUser(receiverId);
                userSet.add(user);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        HtmlUtil htmlUtil = new HtmlUtil();
        for (User user : userSet){
            String senderId = user.getId();
            map.put("id", id);
            map.put("senderId", senderId);
            List<HashMap> maps = chatMapper.searchMyMessage(map);
            Integer notRead = chatMapper.searchIsNotRead(map);
            String string = maps.get(0).get("content").toString();
            String createTime = maps.get(0).get("create_time").toString();
            String content = htmlUtil.convertHtmlToPlainText(string);
            user.setLatestMessage(content);
            user.setLatestTime(createTime);
            user.setNotRead(notRead);
        }
        return new ArrayList<>(userSet);
    }


    @Override
    public Integer addChat(Chat chat) {
        int insert = chatMapper.insert(chat);
        if (insert != 1){
            throw new CunionException("添加失败");
        }
        return insert;
    }

    @Override
    public Integer deletedChat(String chatId) {
        int result = chatMapper.deleteById(chatId);
        if (result != 1){
            throw new CunionException("删除失败！");
        }
        return result;
    }

    @Override
    public Integer updateChat(Chat chat) {
        int result = chatMapper.updateById(chat);
        if (result != 1){
            throw new CunionException("修改失败");
        }
        return result;
    }

    @Override
    public List<Chat> searchChat(Integer start, Integer length) {
        Page<Chat> page = new Page<>(start, length);
        QueryWrapper<Chat> QueryWrapper = new QueryWrapper<>();
        Page<Chat> selectPage = chatMapper.selectPage(page, QueryWrapper);
        List<Chat> list = selectPage.getRecords();
        return list;
    }
}




